//
//  YZMHIStorytackViewController.m
//  YZMicroStock
//
//  Created by apple on 16/11/2.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMHIStorytackViewController.h"
#import "YZMHIStoryTableViewCell.h"
#import <MJRefreshNormalHeader.h>
#import <MJRefreshAutoNormalFooter.h>
#import "YZMPageService.h"
#import "YZClient.h"
#import "YZMHistoryPacket.h"

static NSString *const YZMHIStoryCellID=@"YZMHIStoryTableViewCell";

@interface YZMHIStorytackViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *HIStoryTableview;
@property(nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property (nonatomic, strong) YZMPageService *pageService;
@property(nonatomic, strong) UIImageView *noneCellImage;
@property(nonatomic, strong) UILabel *noneCellLabel;

@end

@implementation YZMHIStorytackViewController

- (id)init {
    if (self = [super init]) {
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.title = @"历史策略组";
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

-(NSMutableArray *)datasource
{
    if (!_datasource) {
        self.datasource=[NSMutableArray array];
    }
    return _datasource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createObject];
    // Do any additional setup after loading the view.
}

-(void)createObject
{
    WS(ws)
    self.HIStoryTableview = [[UITableView alloc]init];
    _HIStoryTableview.delegate=self;
    _HIStoryTableview.dataSource=self;
    _HIStoryTableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _HIStoryTableview.backgroundColor=[YZMAppStyle appBackgroundColor];
    [self.view addSubview:_HIStoryTableview];
    [_HIStoryTableview registerClass:[YZMHIStoryTableViewCell class] forCellReuseIdentifier:YZMHIStoryCellID];
    [_HIStoryTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    self.pageService = [YZMPageService new];
    self.pageService.pageSize = 100;
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fetchFundListFirstPage)];
    _HIStoryTableview.mj_header = _refreshHeader;
    
    _refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(fechFundListNextPage)];
    _HIStoryTableview.mj_footer = _refreshFooter;
    
    [self fetchFundListFirstPageWithRemoveDataFlag:YES];
}

- (void)fetchFundListFirstPage{
    
    [self fetchFundListFirstPageWithRemoveDataFlag:YES];
}

- (void)fetchFundListFirstPageWithRemoveDataFlag:(BOOL)removeFlag{
    
    if (removeFlag) {
        
        [self.datasource removeAllObjects];
        [self.HIStoryTableview reloadData];
    }
    
    [self.pageService preChangeWithPage:self.pageService.minPage andTimeEnd:YES];
    [self getHistoryData];
}


-(void)fechFundListNextPage
{
    if (self.datasource.count == 0) {
        
        [self.pageService preChangeWithPage:self.pageService.minPage andTimeEnd:YES];
    } else {
        
        [self.pageService preChangeWithPage:self.pageService.nextPage  andTimeEnd:YES];
    }
    [self getHistoryData];
}

-(void)getHistoryData
{

    [_refreshFooter resetNoMoreData];
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        [NSError yz_showMessageForNoWifi];
        return;
    }
    [YZClient td_fetchTradeHistoryListForDWithPage:self.pageService.minPage andPageSize:self.pageService.pageSize success:^(NSURLResponse *response, id responseObject) {
        [self endRefresh];
        _HIStoryTableview.mj_header = _refreshHeader;
        _HIStoryTableview.mj_footer = _refreshFooter;
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            YZMHistoryPacket *HisModel=topModel.data;
            NSArray *array = HisModel.dataList;
            NSInteger pageIndex = HisModel.currentPage;
            if (pageIndex==self.pageService.minPage) {
                [self.datasource removeAllObjects];
                [_datasource addObjectsFromArray:array];
                self.pageService.maxPage=HisModel.totalPage;
            }else{
                if (array.count!=0) {
                    [self.datasource addObjectsFromArray:array];
                }
            }
            if (self.datasource.count!=0 && (array.count<self.pageService.pageSize || [_pageService isMaxPage])) {
                [_refreshFooter endRefreshingWithNoMoreData];
                _refreshFooter.stateLabel.text=@"暂无更多记录";
            }else{
                [_refreshFooter resetNoMoreData];
                _refreshFooter.hidden=YES;
            }
            [self.HIStoryTableview reloadData];
            [self.pageService effectChange];
        }
        else{
            if (!_datasource || _datasource.count==0) {
                _HIStoryTableview.mj_header=nil;
                _HIStoryTableview.mj_footer=nil;
            }else{
                [topModel showMessage];
            }
        }
        if (self.datasource.count==0) {
            [self createNoneCell];
        }
    } failure:^(NSError *error) {
        if (self.datasource.count==0) {
            _HIStoryTableview.mj_footer=nil;
            _HIStoryTableview.mj_header=nil;
        }else{
            [error yz_showMessage];
        }
    }];

}

-(void)createNoneCell
{
    if (!_noneCellImage) {
        _noneCellImage=[UIImageView new];
    }
    
    [_noneCellImage setImage:[UIImage imageNamed:@"icon_no_record"]];
    [self.view addSubview:_noneCellImage];
    [_noneCellImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(98);
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(155);
    }];
    
    if (!_noneCellLabel) {
        _noneCellLabel=[YZMAppStyle labelWithLargeWhite];
    }
    _noneCellLabel.text=@"暂无数据";
    [self.view addSubview:_noneCellLabel];
    [_noneCellLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_noneCellImage);
        make.top.mas_equalTo(_noneCellImage.mas_bottom).offset(30);
    }];
}

#pragma MARK tableview

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datasource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YZMHIStoryTableViewCell *Cell=[tableView dequeueReusableCellWithIdentifier:YZMHIStoryCellID forIndexPath:indexPath];
    YZMHistoryModel *model=self.datasource[indexPath.section];
    Cell.model=model;
    Cell.selectionStyle=UITableViewCellSelectionStyleNone;

    return Cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 188;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 14;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *pageName=@"historyList";
    YZMHistoryModel *model=self.datasource[indexPath.section];
    NSDictionary *params = @{@"model":model};
    [YZMCMInstance pushViewControllerWithName:pageName andParams:params];
}


- (void)endRefresh{
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
    
    if (_refreshFooter.isRefreshing) {
        
        [_refreshFooter endRefreshing];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
